package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Override
    public void add(ShoppingCartDTO shoppingCartDTO) {
        //第一步创建查询的实体对象
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        //查询购物车的时候还需要获取用户的id
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        //第二步根据实体对象进行查询数据库，看该条记录是否存在
        ShoppingCart cart =  shoppingCartMapper.query(shoppingCart);
        //第三步，如果存在则获取该条记录的数量+1；
        if(cart != null){
            cart.setNumber(cart.getNumber()+1);
            shoppingCartMapper.update(cart);
        }
        //第四步，如果不存在则进行判断添加的是菜品的信息还是套餐的信息
        else{
            //如果是菜品信息，创建插入的实体对象然后进行插入
            Long dishId = shoppingCartDTO.getDishId();
            if(dishId != null){
                //根据菜品的id获取菜品的信息
                Dish dish = dishMapper.getDishById(dishId);
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
            }
            //如果是套餐信息，创建插入的实体对象然后进行插入
            Long setMealId = shoppingCartDTO.getSetmealId();
            if(setMealId != null){
                //根据套餐的id获取套餐的信息
                Setmeal setmeal = setmealMapper.queryById(setMealId);
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());

            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert( shoppingCart);
        }
    }

    @Override
    public List<ShoppingCart> queryList() {
        //根据用户的id进行查询该用户的购物车中的数据
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.queryList(userId);
        return shoppingCarts;
    }

    @Override
    public void clean() {
        //根据用户的id进行删除购物车中的所有商品
        Long userId = BaseContext.getCurrentId();
        shoppingCartMapper.deleteByUserId(userId);
    }
}
